import core.thread;

import std.concurrency;
import std.socket;

class SimpleThreadingListener : Thread
{
	Socket sock;
	void function(shared(Socket)) handler;

	this(string listen, ushort port, void function(shared(Socket)) handler)
	{
		Socket socket = new Socket(AddressFamily.INET, SocketType.STREAM);
		socket.bind(new InternetAddress(listen, port));
		sock = socket;
		this.handler = handler;
		super.isDaemon(true);
		super(&run);
	}

	private void run()
	{
		thread_attachThis();
		try
		{
			sock.listen(5); // magic number for windows
			while (true)
			{
				spawn(this.handler, cast(shared)sock.accept());
			}
		}
		finally
		{
			thread_detachThis();
		}
	}
}
